/*
 * Ext JS Library 2.0.1
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */


Ext.air.FileProvider = function(config){
    Ext.air.FileProvider.superclass.constructor.call(this);
	
	this.defaultState = {
		mainWindow : {
			width:780,
			height:580,
			x:10,
			y:10
		}
	};
	
    Ext.apply(this, config);
    this.state = this.readState();
	
	var provider = this;	
	var winState = this.state.mainWindow;
	var main = window.nativeWindow;
	main.width = Math.max(winState.width, 200);
	main.height = Math.max(winState.height, 200);
	main.x = winState.x;
	main.y = winState.y;
	
	main.addEventListener(air.Event.CLOSING, function(){
		provider.saveState();
	});	
	main.addEventListener(air.NativeWindowBoundsEvent.MOVE, function(){
		if(main.displayState != air.NativeWindowDisplayState.MINIMIZED && main.width > 100 && main.height > 100) {
			winState.x = main.x;
			winState.y = main.y;
		}
	});	
	main.addEventListener(air.NativeWindowBoundsEvent.RESIZE, function(){
		if (main.displayState != air.NativeWindowDisplayState.MINIMIZED && main.width > 100 && main.height > 100) {
			winState.width = main.width;
			winState.height = main.height;
		}
	});
};

Ext.extend(Ext.air.FileProvider, Ext.state.Provider, {
	file: 'extstate.data',
	
	// private
    readState : function(){
		var stateFile = air.File.applicationStorageDirectory.resolvePath(this.file);
		if(!stateFile.exists){
			return this.defaultState || {};
		}
		
		var stream = new air.FileStream();
		stream.open(stateFile, air.FileMode.READ);
		
		var stateData = stream.readObject();
		stream.close();
		
		return stateData || this.defaultState || {};
    },

    // private
    saveState : function(name, value){
        var stateFile = air.File.applicationStorageDirectory.resolvePath(this.file);
		var stream = new air.FileStream();
		stream.open(stateFile, air.FileMode.WRITE);
		stream.writeObject(this.state);
		stream.close();
    }
});